﻿using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using K9Nano.Admin.Settings.Dto;
using K9Nano.Application;
using K9Nano.Configuration;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.Runtime;
using Microsoft.Extensions.Logging;

namespace K9Nano.Admin.Settings
{
    public class AdminSettingsAppService : K9ApplicationService, IAdminSettingsAppService, IScopedDependency
    {
        protected readonly ISettingManager SettingManager;

        public AdminSettingsAppService(IUnitOfWork uow, IMapper mapper, ISessionContext sessionContext, ILoggerFactory loggerFactory, ISettingManager settingManager) : base(uow, mapper, sessionContext, loggerFactory)
        {
            SettingManager = settingManager;
        }


        #region SMS

        public virtual async ValueTask<SmsVerificationSettingsDto> GetSmsVerificationSettingsAsync(CancellationToken cancellation)
        {
            var dto = new SmsVerificationSettingsDto
            {
                TemplateId = await SettingManager.GetSettingValueAsync(AdminSettingConfiguration.Sms_VerificationTemplateId),
                Length = await SettingManager.GetIntAsync(AdminSettingConfiguration.Sms_VerificationLength),
                Expires = await SettingManager.GetIntAsync(AdminSettingConfiguration.Sms_VerificationExpires),
            };

            return dto;
        }

        public virtual async ValueTask ChangeSmsVerificationSettingsAsync(SmsVerificationSettingsDto dto, CancellationToken cancellation)
        {
            await SettingManager.ChangeSettingAsync(AdminSettingConfiguration.Sms_VerificationTemplateId, dto.TemplateId, SessionContext.TenantId, null);
            await SettingManager.ChangeSettingAsync(AdminSettingConfiguration.Sms_VerificationLength, dto.Length.ToString(), SessionContext.TenantId, null);
            await SettingManager.ChangeSettingAsync(AdminSettingConfiguration.Sms_VerificationExpires, dto.Expires.ToString(), SessionContext.TenantId, null);
        }

        #endregion SMS
    }
}